package com.boot.interceptor;

import com.boot.entity.Result;
import com.boot.service.ILogService;
import com.boot.util.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

import static com.boot.config.WebConfig.OPTIONS;

/**
 * @author bbyh
 * @description 用户限流拦截器
 * @since 2024-04-29
 */
@Component
@Slf4j
public class LimitUserInterceptor implements HandlerInterceptor {
    public static String userInterLimitPrefix;
    public static String userInterLimitSet;
    @Value("${user.inter.limit.count}")
    private Integer userInterLimitCount;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ILogService logService;

    @Value("${user.inter.limit.prefix}")
    public void setUserInterLimitPrefix(String userInterLimitPrefix) {
        LimitUserInterceptor.userInterLimitPrefix = userInterLimitPrefix;
    }

    @Value("${user.inter.limit.set}")
    public void setUserInterLimitSet(String userInterLimitSet) {
        LimitUserInterceptor.userInterLimitSet = userInterLimitSet;
    }

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        try {
            if (OPTIONS.equals(request.getMethod())) {
                return true;
            }

            String ip = IpUtil.getIp(request);
            String username = request.getHeader("username");
            String uri = request.getRequestURI();
            if (username == null) {
                return true;
            }
            String key = userInterLimitPrefix + username;

            Boolean exist = stringRedisTemplate.opsForSet().isMember(userInterLimitSet, key);
            if (Boolean.TRUE.equals(exist)) {
                logService.saveInterLog(ip, username, uri);
                Result.writeResult(response, "用户名：" + username + "已被加入黑名单");
                return false;
            }

            String userCount = stringRedisTemplate.opsForValue().get(key);
            if (userCount == null) {
                stringRedisTemplate.opsForValue().set(key, "1", 60, TimeUnit.SECONDS);
                return true;
            }

            if (Integer.parseInt(userCount.trim()) >= userInterLimitCount) {
                stringRedisTemplate.opsForSet().add(userInterLimitSet, key);
                logService.saveInterLog(ip, username, uri);
                Result.writeResult(response, "用户名：" + username + "请求次数已达到阈值，被加入黑名单");
                return false;
            }
            stringRedisTemplate.opsForValue().set(key, String.valueOf(Integer.parseInt(userCount.trim()) + 1), 0);

            return true;
        } catch (NumberFormatException e) {
            log.error(e.getMessage(), e);
            Result.writeResult(response, "用户限流器服务出错");
            return false;
        }
    }
}
